const indexModule = (function () {
  let $baseBox = $(".baseBox"),
    $baseBoxText = $(".baseBox").find("span"),
    $baseBoxSingout = $(".baseBox").find('a'),
    $menuBox = $(".menuBox"),
    $navBox = $(".navBox"),
    $navBoxList = $navBox.find("a"),
    $itemBoxList = null,
    $iframeBox = $('.iframeBox');

  // 3.基于发布订阅管理我们获取个人信息和权限信息后要处理的事情:
  $plan = $.Callbacks();

  // 5.往计划表中添加任务1 显示欢迎的基本信息和退出登录
  $plan.add((_, baseInfo) => {
    $baseBoxText.html(`您好，${baseInfo.name || ''}`);
    $baseBoxSingout.click(async () => {
      let exitResult = await axios.get("/user/signout");
      if (exitResult.code == 0) {
        // 清理本地缓存
        localStorage.removeItem("departmentInfo");
        localStorage.removeItem("jobInfo");

        alert("退出成功o(*￣▽￣*)ブ");
        window.location.href = 'login.html';
        return;
      }
      alert("登录失败，请重试┭┮﹏┭┮");
    })
  })

  // 任务2 权限处理（控制左侧menu内容渲染）
  $plan.add(power => {
    // console.log(power);
    let str = ``;
    if (power.includes("userhandle")) {
      str += `
      <div class="itemBox" text="员工管理">
        <h3>
          <i class="iconfont icon-yuangong"></i>
          员工管理
        </h3>
        <nav class="item">
          <a href="../page/userlist.html" target="iframeBox">员工列表</a>
          <a href="../page/useradd.html" target="iframeBox">新增员工</a>
        </nav>
      </div>
      `;
    }
    if (power.includes("departhandle")) {
      str += `
      <div class="itemBox" text="部门管理">
				<h3>
					<i class="iconfont icon-guanliyuan"></i>
					部门管理
				</h3>
				<nav class="item">
					<a  href="../page/departmentlist.html" target="iframeBox">部门列表</a>
					<a  href="../page/departmentadd.html" target="iframeBox">新增部门</a>
				</nav>
			</div>
      `;
    }
    if (power.includes("jobhandle")) {
      str += `
      <div class="itemBox" text="职务管理">
				<h3>
					<i class="iconfont icon-zhiwuguanli"></i>
					职务管理
				</h3>
				<nav class="item">
					<a  href="../page/joblist.html" target="iframeBox">职务列表</a>
					<a  href="../page/jobadd.html" target="iframeBox">新增职务</a>
				</nav>
			</div>
      `;
    }
    if (power.includes("customer")) {
      str += `
      <div class="itemBox" text="客户管理">
				<h3>
					<i class="iconfont icon-kehuguanli"></i>
					客户管理
				</h3>
				<nav class="item">
					<a  href="../page/customerlist.html?lx=my" target="iframeBox">我的客户</a>
					${power.includes("customerall") ? `<a  href="../page/customerlist.html?lx=all" target="iframeBox">全部客户</a>` : ``}
					<a  href="../page/customeradd.html" target="iframeBox">新增客户</a>
				</nav>
			</div>
      `;
    }

    $menuBox.html(str);
    $itemBoxList = $menuBox.find(".itemBox");
  })

  // 处理分组
  function handleGroup(index) {
    // $group1 客户管理(userhandle) $group2组织结构(departhandle | jobhandle | customerall)
    let $group1 = $itemBoxList.filter((_, item) => $(item).attr("text") === '客户管理');
    let $group2 = $itemBoxList.filter((_, item) => /^(员工管理|部门管理|职务管理)$/.test($(item).attr("text")));
    // console.log($group1, $group2);

    if (index === 0) {
      $group1.show();
      $group2.hide();
    } else if (index === 1) {
      $group2.show();
      $group1.hide();
    }
  }

  // 任务3 权限处理（控制顶部客户管理和组织结构点击切换）
  $plan.add(power => {
    // 默认第一个显示（索引值后面还要用到）
    let initialIndex = power.includes("custom") ? 0 : 1; // 处理默认权限没有客户管理的
    $navBoxList.eq(initialIndex).addClass("active").siblings("a").removeClass("active");

    handleGroup(initialIndex);

    $navBoxList.click(function () {
      let $this = $(this),
        index = $this.index(),
        text = $this.html().trim();
      //todo 权限校验
      if (text === "客户管理" && !/customer/.test(power)) {
        alert("无权操作，联系管理员┭┮﹏┭┮");
        return;
      }
      if (text === "组织结构" && !/(userhandle|departhandle|jobhandle)/.test(power)) {
        alert("无权操作，联系管理员┭┮﹏┭┮");
        return;
      }
      // 控制展示哪一组
      if (index === initialIndex) return;
      $this.addClass('active');
      $navBoxList.eq(initialIndex).removeClass('active');

      handleGroup(index);

      initialIndex = index;
    })
  })

  // 任务4 权限处理（控制默认进来iframe嵌套的页面）
  $plan.add(power => {
    let url = "../page/customerlist.html?lx=my";
    if (!power.includes("customer")) {
      url = "../page/userlist.html";
    }
    $iframeBox.attr("src", url);
  })

  return {
    async init() {
      // 1.验证是否登录
      let result = await axios.get("/user/login");
      if (result.code != 0) {
        alert("未登录，请前往登录┭┮﹏┭┮");
        window.location.href = "login.html";
        return;
      }

      // 2.获取登录用户的权限信息和个人信息(AJAX并行)
      let [powerInfo, userInfo] = await axios.all([
        axios.get("/user/power"),
        axios.get("/user/info"),
      ]);
      let power = powerInfo.code == 0 ? powerInfo.power : '',
        baseInfo = userInfo.code == 0 ? userInfo.data : "";
      // console.log(powerInfo, baseInfo);
      // 4.通知计划表中的任务执行：
      $plan.fire(power, baseInfo);

    }
  }

})();

indexModule.init();